﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace SocketTest
{
     class socketTCPClient
    {
        //创建一个socket的对象
        public static Socket socketClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        private static byte[] result = new byte[1024];//定义一个字节数组,相当于缓存
        public static string serverIp = "127.0.0.1";//设定服务器IP地址
        public static int serverPort = 8888;//设定服务器端口
       
        /// <summary>
        /// 创建Socket客户端
        /// </summary>
        public static void SocketClient()
        {
            IPAddress ip = IPAddress.Parse(serverIp);//服务器IP地址
            IPEndPoint point = new IPEndPoint(ip, serverPort);//服务器IP地址及端口
            try
            {
                socketClient.Connect(point);//链接服务器IP与端口
                Console.WriteLine("连接服务器成功");
            }
            catch (Exception)
            {
                Console.WriteLine("连接服务器失败，请按回车键退出！");
                return;
            }
            //通过socketClient接受服务器的数据
            int num = socketClient.Receive(result);//把接受到的数据存到bytes数组中并赋值给num
            Console.WriteLine("接收服务器消息：{0}", Encoding.UTF8.GetString(result, 0, num));  //GetString(result, 0, num)把从0到num的字节变成String
            try
            {
                Thread.Sleep(1000);    //等待1秒钟  
                //通过 socketClient 向服务器发送数据
                string sendMessage = "已成功接到SocketClient发送的消息";//发送到服务端的内容
                byte[] send = Encoding.UTF8.GetBytes(sendMessage);//Encoding.UTF8.GetBytes()将字符串转换成字节（避免乱码）
                socketClient.Send(send);  //将接受成功的消息返回给SocketServer服务器 
                Console.WriteLine("发送完毕：{0}", sendMessage);

            }
            catch
            {
                socketClient.Shutdown(SocketShutdown.Both);//禁止Socket上的发送和接受
                socketClient.Close();//关闭Socket并释放资源
            }
            Console.ReadLine();
            socketClient.Close();//关闭Socket并释放资源
        }


    }
}
